<template>
  <el-drawer
    v-model="props.isTitle"
    :title="titles"
    size="52%"
    :close-on-click-modal="false"
    :before-close="guan"
   
  >
    <div class="drawer">
      <div class="radio">
        <el-radio-group
          v-model="params.type"
          class="ml-4"
          @change="changeRadio"
        >
          <el-radio label="单选题" size="large">单选题</el-radio>
          <el-radio label="多选题" size="large">多选题</el-radio>
          <el-radio label="判断题" size="large">判断题</el-radio>
          <el-radio label="填空题" size="large">填空题</el-radio>
          <el-radio label="问答题" size="large">问答题</el-radio>
        </el-radio-group>
      </div>
      <div class="conent">
        <el-form :model="data" class="demo-form-inline" label-width="80px">
          <!-- 编辑器开始 -->
          <el-form-item label="题干">
               <div style="border: 1px solid #ccc">
 <Toolbar
              style="border-bottom: 1px solid #ccc"
              :editor="editorRef"
              :defaultConfig="toolbarConfig"
            />
            <Editor
              style="height: 130px; overflow-y: hidden"
              v-model="params.title"
              :defaultConfig="editorConfig"
              mode="default"
              @onCreated="handleCreated"
            />
               </div>
           
          </el-form-item>
          <!-- 编辑器结束 -->
          <el-form-item
            label="选项"
            v-show="params.type == '单选题' || params.type == '多选题'"
          >
            <div
              class="tiao"
              v-for="(item, index) in params.answers"
              :key="index"
            >
              <span>{{ arr[index] }}：</span>
              <el-input v-model="item.content" type="textarea" />
              <el-icon
                ><CircleClose class="font" @click.prevent="removeDomain(item)"
              /></el-icon>
            </div>
          </el-form-item>
          <el-form-item
            v-show="params.type == '单选题' || params.type == '多选题'"
          >
            <el-icon @click="addDomain"><CirclePlus class="fonts" /></el-icon>
          </el-form-item>
          <!--  -->
          <el-form-item
            label="正确答案"
            v-show="params.type == '单选题'"
            style="margin-top: 10px"
          >
            <el-radio-group
              v-model="params.answer"
              v-for="(item, index) in params.answers"
              class="ml-4"
              :key="index"
            >
              <el-radio :label="arr[index]" size="large"></el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item
            label="正确答案"
            v-show="params.type == '判断题'"
            style="margin-top: 10px"
          >
            <el-radio-group v-model="params.answer" size="large">
              <el-radio-button label="正确" />
              <el-radio-button label="错误" />
            </el-radio-group>
          </el-form-item>
          <!-- 填空题 -->
          <el-form-item
            label="正确答案"
            label-width="90px"
            style="max-width: 460px"
            v-if="topicArr.length > 0"
            v-show="params.type == '填空题'"
          >
            <div class="from">
              <el-input
                v-model="topicArr[index]"
                v-for="(item, index) in topicArr"
                :key="index"
                v-show="params.type == '填空题'"
              />
            </div>
          </el-form-item>
          <el-form-item label="解析" v-show="params.type == '填空题'">
            <el-input
              v-model="params.explains"
              type="textarea"
              style="margin-left: 0px"
            />
          </el-form-item>
          <el-form-item label="解析" v-show="params.type == '问答题'">
            <el-input
              v-model="params.explains"
              type="textarea"
              style="margin-left: 0px"
            />
          </el-form-item>
          <el-form-item
            label="正确答案"
            v-show="params.type == '多选题'"
            style="margin-top: 10px"
          >
            <el-checkbox-group
              v-for="(item, index) in params.answers"
              v-model="check"
              @change="changeCheckbox"
              :key="index"
              class="ml-4"
            >
              <el-checkbox :label="arr[index]" size="large" />
            </el-checkbox-group>
          </el-form-item>
          <el-form-item label="分值">
            <div class="fen">
              <el-input v-model="params.scores" />
            </div>
          </el-form-item>
        </el-form>
        <div class="but">
          <el-button type="primary" @click="save">保存</el-button>
          <el-button @click="continues" v-if="datas.index === -1"
            >保存并继续</el-button
          >
          <el-button @click="qu">取消</el-button>
        </div>
      </div>
    </div>
  </el-drawer>
</template>

<script lang="ts" setup>
import {reactive, toRefs, watch, inject, defineEmits,computed, onMounted} from "vue";
import { CircleClose, CirclePlus } from "@element-plus/icons-vue";
// 引入编辑器
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { ElMessage } from "element-plus";
import "@wangeditor/editor/dist/css/style.css"; // 引入 css

import { onBeforeUnmount, ref, shallowRef } from "vue";
const data: any = reactive({
  // drawer: false,
  // 多选框
  check: <any>[],
  params: {
    // 正确答案
    answer: <any>null,
    // 类型
    type: "单选题",
    scores: "",
    // 在线编辑器
    title: "",
    tags: "",
    // 答案解析
    explains: "",
    answers: [
      { answerno: "A", content: "" },
      { answerno: "B", content: "" },
      { answerno: "C", content: "" },
      { answerno: "D", content: "" },
    ],
  },
  arr: [
    "A",
    "B",
    "C",
    "D",
    "E",
    "F",
    "G",
    "H",
    "I",
    "J",
    "K",
    "L",
    "M",
    "N",
    "O",
    "P",
    "Q",
    "R",
    "S",
    "T",
    "U",
    "V",
    "W",
    "X",
    "Y",
    "Z",
  ],
  topicArr: [],
 
});
const { topicArr, drawer, params, arr, check }: any = toRefs(data);

const datas: any = inject("data");
watch([datas], () => {
  data.check = datas.obj.answer;
});
const props: any = defineProps({
  isTitle: Boolean,
  obj: <any>null,
  index: Number,
});
onMounted(()=>{
  data.params ={... data.params,...props.obj};
  if (typeof props.obj.answer === "string") {
    data.topicArr = props.obj.answer.split("|");
    data.check = props.obj.answer.split("|");
  }
})
const titles = computed(() => props.index < 0 ?  "试题添加" :  "试题修改")
// 多选框内容改变
const changeCheckbox = (e: any) => {
  data.params.answer = e;
};
// 点击加号加一
const addDomain = () => {
  if (data.arr.length === params.value.answers.length) {
    ElMessage("只能填这么多选项了！");
    return;
  }
  params.value.answers.push({
    answerno: arr.value[params.value.answers.length],
  });
};
// 删除
const removeDomain = (item: any) => {
  const index = params.value.answers.indexOf(item);
  if (index !== -1) {
    params.value.answers.splice(index, 1);
  }
};
const guan = () => {
  check.value = [];
  data.topicArr = [];
  emit("isF", false);
};
// 保存
const save = () => {
  if (params.value.type === "单选题" || params.value.type === "多选题") {
    if (!params.value.answer) {
      ElMessage("正确答案必填！");
      return;
    } else if (!params.value.scores) {
      ElMessage("请输入分值");
      return;
    }
    var noNum: number = 0;
    params.value.answers.map((item: any) => {
      if (!item.content) {
        noNum += 1;
      }
    });
    if (noNum > 0) {
      ElMessage("选项答案必填！");
      return;
    }
  }
  if (params.value.type === "判断题") {
    if (!params.value.answer) {
      ElMessage("请输入正确答案");
      return;
    }
    if (!params.value.scores) {
      ElMessage("请输入分值");
      return;
    }
  }

  if (params.value.type === "填空题" || params.value.type === "问答题") {
    params.value.answer = data.topicArr.join("|");
    if (!params.value.scores) {
      ElMessage("请输入分值");
      return;
    }
  }
  emit("isF", false);
  if (props.index < 0) {
    datas.params.questions.push(JSON.parse(JSON.stringify(params.value)));
  } else {
    datas.params.questions[props.index] = JSON.parse(JSON.stringify(params.value));
    datas.index = -1;
  }
  check.value = [];
  data.topicArr = [];
};
const emit = defineEmits(["isF", "copy", "edi"]);
// 取消
const qu = () => {
  check.value = [];
  data.topicArr = [];
  emit("isF", false);
};
// 保存并继续
const continues = () => {
  if (params.type === "单选题" || params.type === "多选题") {
    if (!params.value.answer) {
      ElMessage("正确答案必填！");
      return;
    } else if (!params.value.scores) {
      ElMessage("请输入分值");
      return;
    }
  }

  if (params.value.type === "判断题") {
    if (!params.value.answer) {
      ElMessage("请输入正确答案");
      return;
    }
    if (!params.value.scores) {
      ElMessage("请输入分值");
      return;
    }
  }

  if (params.value.type === "填空题" || params.value.type === "问答题") {
    if (!params.value.scores) {
      ElMessage("请输入分值");
      return;
    }
  }
  const obj = JSON.stringify(params.value);
  datas.params.questions.push(JSON.parse(obj));
  data.topicArr = [];
  params.value.scores = "";
  // params.value.title = "";
  params.value.answer = "";
  params.value.explains = "";
  params.value.answers.map((item: any) => (item.content = ""));
};
// 单选框内容改变
const changeRadio = (e: any) => {
  params.value.answer = "";
  params.value.explains = "";
  params.value.answers.map((item: any) => (item.content = ""));
};
// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef();
// 内容 HTML
watch(() => params.value.title,(newValue: any, oldValue: any) => {
    if (data.params.type == "填空题") {
      if (newValue.match(/\[\]/g) !== null) {
        let _inputNum = newValue.match(/\[\]/g).map((item: any, index: number) => (item = data.topicArr[index]));
        data.topicArr = [..._inputNum];
      }
    }
  },{ immediate: false, deep: true });

const toolbarConfig = {
  toolbarKeys: [
    // 菜单 key
    "bold",
    "italic",
    "underline",
    "through",
    "color",
    "bgColor",
    "bulletedList",
    "numberedList",
    "justifyLeft",
    "justifyCenter",
    "justifyRight",
    "insertTable",
    // 继续配置其他菜单...
    {
      key: "group-image", // 必填，要以 group 开头
      title: "图片", // 必填
      menuKeys: ["uploadImage", "insertImage"],
    },
  ],
};
const editorConfig: any = { MENU_CONF: {} };

editorConfig.MENU_CONF["uploadImage"] = {
  server: import.meta.env.VITE_BASE_URL + "upload/editeradd", // 上传图片地址
  timeout: 5 * 1000, // 5s
  fieldName: "file",
  meta: { baseUrl: "" },
  metaWithUrl: true, // 参数拼接到 url 上
  headers: { Authorization: sessionStorage.getItem("token") },

  maxFileSize: 10 * 1024 * 1024, // 10M

  base64LimitSize: 5 * 1024, // 5kb 以下插入 base64

  onBeforeUpload(files: any) {
    console.log("onBeforeUpload", files);
    return files; // 返回哪些文件可以上传
  },
  onProgress(progress: any) {
    console.log("onProgress", progress);
  },
  onSuccess(file: any, res: any) {
    console.log("onSuccess", file, res);
  },
  onFailed(file: any, res: any) {
    alert(res.message);
    console.log("onFailed", file, res);
  },
  onError(file: any, err: any, res: any) {
    alert(err.message);
    console.error("onError", file, err, res);
  },
  // // 用户自定义插入图片
  customInsert(res: any, insertFn: any) {
    var Img = res.data[0].url.slice(1);
    // 自己插入图片
    // console.log('自己插入图片', url)
    // insertFn(url, alt, href)
    insertFn("http://www.eshareedu.cn/exam/upload/" + Img);
  },
};

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor == null) return;
  editor.destroy();
});

const handleCreated = (editor: any) => {
  editorRef.value = editor; // 记录 editor 实例，重要！
};
</script>
<style scoped lang="less">
@import url("../../static/css/test/drawer.css");
</style>